/**
 *
 * @description: 新增图书
 * @author: junyong.hong
 * @createTime: 2018/6/6
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */

const https = require('https')
const { mysql } = require('../qcloud')

// 新增图书
// 1、获取豆瓣信息
// 2、入库
module.exports = async (ctx) => {
  // post提交过来的参数
    const { isbn, openid } = ctx.request.body
    if (isbn && openid) {
    // 查询书籍是否已经存在
        const findRes = await mysql('books').select().where('isbn', isbn)
        if (findRes.length) {
            ctx.state = {
                code: -1,
                data: {
                    msg: '图书已经存在'
                }
            }
            return
        }

        let url = 'https://api.douban.com/v2/book/isbn/' + isbn
        const bookinfo = await getJSON(url)

    // 评分
        const rate = bookinfo.rating.average
        const { title, image, alt, publisher, summary, price } = bookinfo

    // bookinfo请求到的tags数据如下
    // tags:
    //   [ { count: 11323, name: '数学', title: '数学' },
    //     { count: 4759, name: '计算机', title: '计算机' },
    //     { count: 3903, name: '科普', title: '科普' },
    //     { count: 2936, name: '吴军', title: '吴军' },
    //     { count: 2087, name: '计算机科学', title: '计算机科学' },
    //     { count: 1868, name: '互联网', title: '互联网' },
    //     { count: 1233, name: '科学', title: '科学' },
    //     { count: 727, name: 'Programming', title: 'Programming' } ],
        const tags = bookinfo.tags.map(v => {
            return `${v.title} ${v.count}`
        }).join(',')
        const author = bookinfo.author.join(',')

        try {
            await mysql('books').insert({
                isbn, openid, rate, title, image, alt, publisher, summary, price, tags, author
            })
            ctx.state.data = {
                title,
                msg: 'success'
            }
        } catch (e) {
            ctx.state = {
                code: -1,
                data: {
                    msg: '新增失败' + e.sqlMessage
                }
            }
        }
    }
}

/**
 * 把数据转成json格式
 * @param url
 * @returns {Promise}
 */
function getJSON (url) {
    return new Promise((resolve, reject) => {
        https.get(url, res => {
            let urlData = ''
            // 每当接收到请求体数据，累加到post中
            res.on('data', data => {
                urlData += data
            })
            // 数据读完后产生的事件
            res.on('end', data => {
                const bookinfo = JSON.parse(urlData)
                if (bookinfo.title) {
                    resolve(bookinfo)
                }
                reject(bookinfo)
            })
        })
    })
}
